package com.wy.controller;

import com.wy.pojo.OpenCourse;
import com.wy.pojo.OpenCourseAndScore;
import com.wy.pojo.Student;
import com.wy.pojo.Teacher;
import com.wy.service.CourseGradeService;
import com.wy.service.OpenCourseService;
import com.wy.utils.JsonUtil;
import com.wy.utils.PageResult;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/openCourse")
public class OpenCourseController {

    @Autowired
    OpenCourseService service;
    @Autowired
    CourseGradeService courseGradeService;
    /**
     * 查询开课
     * @param page  当前页码
     * @param limit 每页大小
     * @return 开课信息
     */
    @RequestMapping({"queryOpenCourses.do", "teacher/queryOpenCourses.do"})
    public PageResult queryOpenCourses(Integer page, Integer limit){
        //获取开课数量
        int count = service.getOpenCoursesCount();
        //获取数据
        List<OpenCourse> openCourses = service.findOpenCoursesByPage(page,limit);
        //返回结果
        return PageResult.success(count, openCourses);
    }

    /**
     * 查询开课(教师权限)
     * @param page  当前页码
     * @param limit 每页大小
     * @return 开课信息
     */
    @RequestMapping("teacher/queryOpenCoursesByTeacher.do")
    public PageResult queryOpenCoursesByTeacher(Integer page, Integer limit, HttpServletRequest req){
        //获取当前账号信息
        Teacher loginTeacher =  (Teacher) req.getSession().getAttribute("loginObj");
        //获取开课数量
        int count = service.getOpenCoursesCountByTeacher(loginTeacher.getTid());
        //获取数据
        List<OpenCourse> openCourses = service.findOpenCoursesByPageByTeacher(page,limit,loginTeacher.getTid());
        //返回结果
        return PageResult.success(count, openCourses);
    }

    /**
     * 查询(学生权限)
     * @return 开课信息
     */
@RequestMapping("student/queryOpenCoursesByStudent.do")
public PageResult queryOpenCoursesByStudent(String year, Integer term, HttpServletRequest req) {
    // 获取当前登录学生的信息
    Student loginStudent = (Student) req.getSession().getAttribute("loginObj");
    if (loginStudent == null) {
        return PageResult.error("用户未登录");
    }

    // 将学期数字转换为对应的中文
    String termStr = null;
    if (term != null) {
        switch (term) {
            case 1:
                termStr = "第一学期";
                break;
            case 2:
                termStr = "第二学期";
                break;
            default:
                termStr = null;
                break;
        }
    }

    // 调用服务层查询数据
    List<OpenCourseAndScore> openCourseAndScores = service.findOpenCoursesByStudent(
            loginStudent.getSid(), year, termStr);

    // 获取总记录数
    int total = openCourseAndScores.size();

    // 返回查询结果
    return PageResult.success(total, openCourseAndScores);
}



    /**
     * 查询所有开课
     * @return 开课信息
     */
    @RequestMapping("queryAllOpenCourses.do")
    public List<OpenCourse> queryAllOpenCourses(){
        return service.findAllOpenCourses();
    }

    /**
     * 删除开课
     * @param json 开课对象的json
     * @return 成功行数
     */
    @RequestMapping("deleteOpenCourses.do")
    public Integer deleteOpenCourses(String json){
        if(json.charAt(0) != '[') json = '[' + json + ']';  //如果不是数组形式，变成数组形式
        List<OpenCourse> openCourses = JsonUtil.parseList(json, OpenCourse.class);
        return service.deleteOpenCourses(openCourses);
    }

    /**
     * 添加一个开课
     * @param json 开课对象的json
     * @return 成功标志1
     */
    @RequestMapping("addOpenCourse.do")
    public Integer addOpenCourse(String json){
        OpenCourse openCourse = JsonUtil.parseObject(json, OpenCourse.class);
        return service.addOpenCourse(openCourse);
    }

    /**
     * 修改一个开课
     * @param json 开课对象的json
     * @return 成功标志1
     */
    @RequestMapping("updateOpenCourse.do")
    public Integer updateOpenCourse(String json){
        OpenCourse openCourse = JsonUtil.parseObject(json, OpenCourse.class);
        return service.updateOpenCourse(openCourse);
    }

    /**
     * 获取开课总数
     * @return 开课总数
     */
    @RequestMapping("getAmount.do")
    public Integer getAmount() {
        return service.getOpenCoursesCount();
    }

    /**
     * 搜索开课
     * @param page 当前页码
     * @param limit 每页大小
     * @param json 搜索参数的json
     *             {"year":学年,"term":学期,"cid":班级id,"tid":教师id,"courseId":课程id}
     * @return 开课信息
     */
    @RequestMapping({"searchOpenCourses.do", "student/searchOpenCourses.do", "teacher/searchOpenCourses.do"})
    public PageResult searchOpenCourses(Integer page, Integer limit, String json){
        //获得搜索的参数
        Map<String, Object> searchParam = JsonUtil.parseMap(json, String.class, Object.class);
        //获取查询个数
        int count = service.getSearchCount(searchParam);
        //查询数据
        List<OpenCourse> openCourses = service.searchOpenCourses(page, limit, searchParam);
        //返回结果
        return PageResult.success(count, openCourses);
    }
@RequestMapping("exportScores.do")
@ResponseBody
public void exportScores(@RequestParam("year") String year,
                          @RequestParam("term") String term,
                         HttpServletRequest req, // 接收学生 ID
                          HttpServletResponse response) throws IOException {

    // 格式化 term 参数
    if ("1".equals(term)) {
        term = "第一学期";
    } else if ("2".equals(term)) {
        term = "第二学期";
    }

    if (!year.endsWith("学年")) {
        year += "学年";   // 自动补全学年后缀
    }
    // 获取当前登录学生的信息
    Student loginStudent = (Student) req.getSession().getAttribute("loginObj");
    // 查询成绩数据，传入学生 ID
    List<OpenCourseAndScore> scores = courseGradeService.queryScoresForExport(year, term, loginStudent.getSid());

    if (scores == null || scores.isEmpty()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("未查询到任何数据，无法导出！");
        return;
    }

    // 创建 Excel 工作簿并填充数据...
    Workbook workbook = new XSSFWorkbook();
    Sheet sheet = workbook.createSheet("成绩表");
    Row headerRow = sheet.createRow(0);
    headerRow.createCell(0).setCellValue("学年");
    headerRow.createCell(1).setCellValue("学期");
    headerRow.createCell(2).setCellValue("教师名");
    headerRow.createCell(3).setCellValue("课程名");
    headerRow.createCell(4).setCellValue("备注");
    headerRow.createCell(5).setCellValue("分数");

    int rowNum = 1;
    for (OpenCourseAndScore score : scores) {
        Row row = sheet.createRow(rowNum++);
        row.createCell(0).setCellValue(score.getYear());
        row.createCell(1).setCellValue(score.getTerm());
        row.createCell(2).setCellValue(score.getTname());  // 教师名
        row.createCell(3).setCellValue(score.getCourseName());  // 课程名
        row.createCell(4).setCellValue(score.getRemark());
        row.createCell(5).setCellValue(score.getScore());
    }

    // 设置响应头并输出文件
    String fileName = "成绩表_" + System.currentTimeMillis() + ".xlsx";
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    workbook.write(response.getOutputStream());
    workbook.close();
}

}
